﻿using System;
using System.Collections.Generic;
using LL.Business;
using NanoERP.Model.Poco;
using NanoERP.Model.SystemMgmt;
using Omu.ValueInjecter;

namespace NanoERP.Business.Permission
{
    /// <summary>
    /// 部门表逻辑
    /// </summary>
    public class DepartmentService : ServiceBase
    {
        /// <summary>
        /// 获得整个部门树
        /// </summary>
        /// <returns></returns>
        public IList<DepartmentTree> GetDepartmentTree()
        {
            var root = new DepartmentTree();

            var list = new List<DepartmentTree>();
            var topDepartments = DbSession.Query<SYS_Department>("ParentId is null");
            foreach (var department in topDepartments)
            {
                var newItem = new DepartmentTree();
                newItem.InjectFrom(department);
                FillChildDepartment(newItem, true);
                list.Add(newItem);
            }
            return list;
        }

        /// <summary>
        /// 填充子部门
        /// </summary>
        /// <param name="department">需要被填充的部门对象</param>
        /// <param name="recursion">是否需要递归调用</param>
        public void FillChildDepartment(DepartmentTree department, bool recursion = false)
        {
            var list = new List<DepartmentTree>();
            var departments = DbSession
                .Query<SYS_Department>("ParentId=@0", department.Id);
            foreach (var dep in departments)
            {
                var newItem = new DepartmentTree();
                newItem.InjectFrom(dep);
                if (recursion)
                    FillChildDepartment(newItem, true);
                department.AddToChildren(newItem);
            }
        }

        public void InsertDepartment(SYS_Department department)
        {
            DbSession.Insert(department);
        }

        public void UpdateDepartment(SYS_Department departmentId)
        {
            var department = new SYS_Department();
            department.InjectFrom(departmentId);

            if (DbSession.Exist<SYS_Department>(department.Id))
            {
                DbSession.Update(department);
                return;
            }
            DbSession.Insert(department);
        }

        public void DeleteDepartment(Guid departmentId)
        {
            DbSession.Delete<SYS_Department>(departmentId);
        }

        public void Move(Guid sourceDepartmentId, Guid? targetDepartmentId)
        {
            var dep = DbSession.Get<SYS_Department>(sourceDepartmentId);
            dep.ParentId = targetDepartmentId;
            DbSession.Update(dep);
        }


        public SYS_Department Get(Guid id)
        {
            return DbSession.Get<SYS_Department>(id);
        }
    }
}
